package com.wang.study.controller;

import com.alibaba.fastjson.JSONObject;
import com.wang.study.Proxy.JdkDynamicProxyUtil;
import com.wang.study.commons.BaseServlet;
import com.wang.study.model.Category;
import com.wang.study.service.CategoryService;
import com.wang.study.service.impl.CategoryServiceImp;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/category.do")
public class CategoryController extends BaseServlet {

    private CategoryService categoryService =  new JdkDynamicProxyUtil<CategoryService>().getProxyObject(new CategoryServiceImp());

    /**
     * 查询所有商品的大类信息
     * @param req
     * @param resp
     * @throws IOException
     */
    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Category> categories = categoryService.findAll();
        resp.getWriter().write(new JSONObject().toJSONString(categories));
    }

    /**
     * 修改大类
     * @param req
     * @param resp
     * @throws IOException
     */
    public void updateById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String status = req.getParameter("status");
        Integer i= categoryService.updateById(Integer.valueOf(id),name,Integer.valueOf(status));
        resp.getWriter().write(new JSONObject().toJSONString(i>0?i:0));
    }

    /**
     * 删除大类
     * @param req
     * @param resp
     * @throws IOException
     */
    public void delById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        Integer i= categoryService.delById(Integer.valueOf(id));
        resp.getWriter().write(new JSONObject().toJSONString(i>0?i:0));
    }

    /**
     * 添加大类信息
     * @param req
     * @param resp
     */
    public void addCategory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        String status = req.getParameter("status");
        String id = req.getParameter("id");
        Integer i= categoryService.addCategory(Integer.valueOf(id),name,Integer.valueOf(status));
        System.out.println(i);
        resp.getWriter().write(new JSONObject().toJSONString(i>0?i:0));
    }
}
